/*
 * Debts Manager. Simple android application for managing debts.
 * Copyright (C) 2010 Maxim Manuylov
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
 */

package manuylov.maxim.dm.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import manuylov.maxim.common.util.IntentUtil;
import manuylov.maxim.dm.Constants;
import manuylov.maxim.dm.R;
import manuylov.maxim.dm.data.DataManager;
import manuylov.maxim.dm.data.object.Person;
import manuylov.maxim.dm.data.object.SubjectEx;
import manuylov.maxim.dm.data.util.DataActionResultProcessor;
import manuylov.maxim.dm.data.util.DataProcessor;
import manuylov.maxim.dm.data.util.DataUtil;

import java.util.List;

public class GroupedBalance extends BaseBalanceActivity {
    private final static String PROPERTY_SPINNER_POSITION = "spinnerPosition";

    private int mySpinnerPosition;
    private ListView myBalanceList;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grouped_balance);

        setTitle(getIntent());

        doRestoreState(savedInstanceState);

        myBalanceList = (ListView) findViewById(R.id.grouped_balance_list);
        myBalanceList.setEmptyView(findViewById(R.id.empty_list_view));

        myBalanceList.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
                if (mySpinnerPosition == Constants.SUBJECT) return;
                final Intent intent = IntentUtil.prepareExplicitIntent(GroupedBalance.this, Constants.ACTION_VIEW_BALANCE_BY_PERSON, BalanceByPerson.class);
                intent.putExtra(Constants.BALANCE_MODE, myBalanceMode);
                final Person person = (Person) parent.getItemAtPosition(position);
                intent.putExtra(Constants.PERSON_ID, person.getId());
                intent.putExtra(Constants.PERSON_NAME, person.getName());
                startActivityForResult(intent, Constants.REQUEST_DEFAULT);
            }
        });

        final Spinner spinner = (Spinner) findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(final AdapterView<?> parent, final View view, final int position, final long id) {
                regroupList(position);
            }

            public void onNothingSelected(final AdapterView<?> parent) {
                // Do nothing
            }
        });

        reloadData();
    }

    @Override
    protected void onRestoreInstanceState(final Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        doRestoreState(savedInstanceState);
    }

    private void doRestoreState(final Bundle savedInstanceState) {
        if (savedInstanceState == null) return;
        ((Spinner) findViewById(R.id.spinner)).setSelection(savedInstanceState.getInt(PROPERTY_SPINNER_POSITION, Constants.PERSON));
    }

    @Override
    protected void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(PROPERTY_SPINNER_POSITION, ((Spinner) findViewById(R.id.spinner)).getSelectedItemPosition());
    }

    @Override
    protected void reloadData() {
        regroupList(mySpinnerPosition);
    }

    private void regroupList(final int spinnerPosition) {
        mySpinnerPosition = spinnerPosition;

        DataUtil.perfromDataAction(this, R.string.loading, new DataProcessor<ListAdapter>() {
            public ListAdapter process(final DataManager dataManager) {
                ListAdapter adapter = null;
                if (mySpinnerPosition == Constants.PERSON) {
                    adapter = new ArrayAdapter<Person>(GroupedBalance.this, android.R.layout.simple_list_item_1, dataManager.getActivePersons(myBalanceMode));
                } else if (mySpinnerPosition == Constants.SUBJECT) {
                    adapter = new SubjectsAdapter(GroupedBalance.this, dataManager.getActiveSubjectsWithBalance(myBalanceMode));
                }
                return adapter;
            }
        }, new DataActionResultProcessor<ListAdapter>() {
            public Void process(final ListAdapter adapter) {
                myBalanceList.setAdapter(adapter);
                return null;
            }
        });
    }

    private static class SubjectsAdapter extends ArrayAdapter<SubjectEx> {
        public SubjectsAdapter(final Context context, final List<SubjectEx> subjects) {
            super(context, android.R.layout.simple_list_item_2, android.R.id.text1, subjects);
        }

        @Override
        public boolean isEnabled(final int position) {
            return false;
        }

        @Override
        public View getView(final int position, final View convertView, final ViewGroup parent) {
            final View view = super.getView(position, convertView, parent);
            final TextView text2 = (TextView) view.findViewById(android.R.id.text2);

            final SubjectEx subjectEx = (SubjectEx) getItem(position);
            final StringBuilder balance = new StringBuilder("");
            final int subjectBalance = subjectEx.getSubjectBalance();

            int balanceColor;
            if (subjectBalance > 0) {
                balance.append("+");
                balanceColor = Color.GREEN;
            } else if (subjectBalance < 0) {
                balanceColor = Color.RED;
            } else {
                balanceColor = Color.YELLOW;
            }

            balance.append(subjectBalance);

            text2.setText(balance.toString());
            text2.setTextColor(balanceColor);

            return view;
        }
    }
}
